<template>
  <view class="address-edit">
    <!-- 页面头部 -->
    <view class="page-header">
      <view class="header-bg"></view>
      <view class="header-content">
        <view class="page-title">{{ isEdit ? '编辑地址' : '新增地址' }}</view>
        <view class="page-subtitle">{{ isEdit ? '修改地址信息' : '添加新的收货地址' }}</view>
      </view>
    </view>

    <view class="content-container">
      <form @submit="submitForm">
        <!-- 联系人信息卡片 -->
        <view class="form-card">
          <view class="card-header">
            <view class="header-left">
              <view class="icon-wrapper contact-icon">
                <uni-icons type="contact-filled" size="20" color="#fff"></uni-icons>
              </view>
              <text class="card-title">联系人信息</text>
            </view>
          </view>
          
          <view class="card-content">
            <!-- 姓名输入 -->
            <view class="form-item">
              <view class="item-label">
                <text class="label-text">收货人</text>
                <text class="required">*</text>
              </view>
              <view class="input-wrapper">
                <input
                  v-model="formData.name"
                  type="text"
                  placeholder="请输入收货人姓名"
                  maxlength="20"
                  class="form-input"
                  :class="{ error: errors.name }"
                  @blur="validateField('name')"
                />
                <uni-icons v-if="formData.name" type="clear" size="16" color="#c0c4cc" @click="formData.name = ''"></uni-icons>
              </view>
              <text v-if="errors.name" class="error-text">{{ errors.name }}</text>
            </view>
            
            <!-- 手机号输入 -->
            <view class="form-item">
              <view class="item-label">
                <text class="label-text">手机号码</text>
                <text class="required">*</text>
              </view>
              <view class="input-wrapper">
                <input
                  v-model="formData.phone"
                  type="number"
                  placeholder="请输入11位手机号码"
                  maxlength="11"
                  class="form-input"
                  :class="{ error: errors.phone }"
                  @blur="validateField('phone')"
                />
                <uni-icons v-if="formData.phone" type="clear" size="16" color="#c0c4cc" @click="formData.phone = ''"></uni-icons>
              </view>
              <text v-if="errors.phone" class="error-text">{{ errors.phone }}</text>
            </view>
            
            <!-- 性别和标签选择 -->
            <view class="form-row">
              <view class="form-item half">
                <view class="item-label">
                  <text class="label-text">称呼</text>
                </view>
                <view class="radio-group">
                  <view 
                    class="radio-item" 
                    :class="{ active: formData.gender === 'male' }"
                    @click="formData.gender = 'male'">
                    <view class="radio-check">
                      <view v-if="formData.gender === 'male'" class="check-dot"></view>
                    </view>
                    <text>先生</text>
                  </view>
                  <view 
                    class="radio-item" 
                    :class="{ active: formData.gender === 'female' }"
                    @click="formData.gender = 'female'">
                    <view class="radio-check">
                      <view v-if="formData.gender === 'female'" class="check-dot"></view>
                    </view>
                    <text>女士</text>
                  </view>
                </view>
              </view>
              
              <view class="form-item half">
                <view class="item-label">
                  <text class="label-text">地址标签</text>
                </view>
                <view class="tag-group">
                  <view 
                    v-for="tag in addressTags" 
                    :key="tag.value"
                    class="tag-item" 
                    :class="{ active: formData.type === tag.value }"
                    @click="formData.type = tag.value">
                    <uni-icons :type="tag.icon" size="14" :color="formData.type === tag.value ? '#fff' : '#999'"></uni-icons>
                    <text>{{ tag.label }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 地址信息卡片 -->
        <view class="form-card">
          <view class="card-header">
            <view class="header-left">
              <view class="icon-wrapper location-icon">
                <uni-icons type="location-filled" size="20" color="#fff"></uni-icons>
              </view>
              <text class="card-title">地址信息</text>
            </view>
          </view>
          
          <view class="card-content">
            <!-- 地区选择 -->
            <view class="form-item">
              <view class="item-label">
                <text class="label-text">所在地区</text>
                <text class="required">*</text>
              </view>
              <picker 
                mode="region" 
                :value="regionArray" 
                @change="onRegionChange"
                class="region-picker-component">
                <view class="picker-wrapper">
                  <view class="picker-content" :class="{ placeholder: !regionText, error: errors.region }">
                    <text>{{ regionText || '请选择省市区' }}</text>
                    <uni-icons type="right" size="16" color="#c0c4cc"></uni-icons>
                  </view>
                </view>
              </picker>
              <text v-if="errors.region" class="error-text">{{ errors.region }}</text>
            </view>
            
            <!-- 详细地址 -->
            <view class="form-item">
              <view class="item-label">
                <text class="label-text">详细地址</text>
                <text class="required">*</text>
              </view>
              <view class="textarea-wrapper">
                <textarea
                  v-model="formData.detail"
                  placeholder="请输入街道、门牌号等详细信息"
                  maxlength="200"
                  auto-height
                  class="form-textarea"
                  :class="{ error: errors.detail }"
                  @blur="validateField('detail')"
                />
                <view class="char-count">{{ formData.detail.length }}/200</view>
              </view>
              <text v-if="errors.detail" class="error-text">{{ errors.detail }}</text>
            </view>
            
            <!-- 位置获取 -->
            <view class="location-actions">
              <view class="action-button location-btn" @click="getCurrentLocation">
                <uni-icons type="location" size="18" color="#667eea"></uni-icons>
                <text>获取当前位置</text>
              </view>
              <view class="action-button map-btn" @click="selectFromMap">
                <uni-icons type="map-pin" size="18" color="#27ae60"></uni-icons>
                <text>地图选择</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 设置选项卡片 -->
        <view class="form-card">
          <view class="card-header">
            <view class="header-left">
              <view class="icon-wrapper setting-icon">
                <uni-icons type="gear-filled" size="20" color="#fff"></uni-icons>
              </view>
              <text class="card-title">设置选项</text>
            </view>
          </view>
          
          <view class="card-content">
            <!-- 设为默认地址 -->
            <view class="form-item switch-item">
              <view class="switch-info">
                <text class="switch-label">设为默认地址</text>
                <text class="switch-desc">将此地址设为默认收货地址</text>
              </view>
              <switch 
                :checked="formData.isDefault" 
                @change="onDefaultChange"
                color="#667eea"
                class="address-switch"
              />
            </view>
          </view>
        </view>
      </form>
    </view>

    <!-- 底部操作区 -->
    <view class="bottom-section">
      <view class="submit-button" :class="{ disabled: !isFormValid }" @click="submitForm">
        <text class="submit-text">{{ isEdit ? '保存修改' : '保存地址' }}</text>
      </view>
    </view>

    <!-- 地区选择器 -->
    <picker-view v-if="showRegionSelector" class="region-picker" @change="onRegionChange">
      <!-- 这里需要实现地区选择器 -->
    </picker-view>
  </view>
</template>

<script>
import { addAddress, updateAddress, getAddressById } from '@/api/user/address'
export default {
  data() {
    return {
      isEdit: false,
      addressId: '',
      formData: {
        name: '',
        phone: '',
        gender: 'male',
        type: 'home',
        province: '',
        city: '',
        district: '',
        detail: '',
        isDefault: false
      },
      errors: {},
      showRegionSelector: false,
      addressTags: [
        { label: '家', value: 'home', icon: 'home' },
        { label: '公司', value: 'company', icon: 'shop' },
        { label: '学校', value: 'school', icon: 'staff' }
      ]
    }
  },
  
  computed: {
    regionText() {
      const { province, city, district } = this.formData
      if (province && city && district) {
        return `${province} ${city} ${district}`
      }
      return ''
    },
    
    regionArray() {
      // 返回当前选中的地区数组，用于picker组件
      const { province, city, district } = this.formData
      if (province && city && district) {
        return [province, city, district]
      }
      return []
    },
    
    isFormValid() {
      return this.formData.name.trim() && 
             this.formData.phone.trim() && 
             this.formData.province && 
             this.formData.city && 
             this.formData.district && 
             this.formData.detail.trim()
    }
  },
  
  onLoad(options) {
    if (options.id) {
      this.isEdit = true
      this.addressId = options.id
      this.loadAddressDetail()
    }
  },
  
  methods: {
    async loadAddressDetail() {
      try {
        uni.showLoading({ title: '加载中...' })
        const res = await getAddressById(this.addressId)
        // 映射API返回的字段到前端表单字段
        this.formData = {
          name: res.data.name || '',
          phone: res.data.phone || '',
          gender: res.data.gender || 'male',
          type: res.data.type || 'home',
          province: res.data.province || '',
          city: res.data.city || '',
          district: res.data.district || '',
          detail: res.data.detail || '',
          isDefault: res.data.is_default || false
        }
        
        uni.hideLoading()
        
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '加载地址信息失败',
          icon: 'none'
        })
      }
    },
    
    validateField(field) {
      this.errors = { ...this.errors }
      delete this.errors[field]
      
      switch (field) {
        case 'name':
          if (!this.formData.name.trim()) {
            this.errors.name = '请输入收货人姓名'
          } else if (this.formData.name.length < 2) {
            this.errors.name = '姓名至少2个字符'
          }
          break
          
        case 'phone':
          const phoneReg = /^1[3-9]\d{9}$/
          if (!this.formData.phone.trim()) {
            this.errors.phone = '请输入手机号码'
          } else if (!phoneReg.test(this.formData.phone)) {
            this.errors.phone = '请输入正确的手机号码'
          }
          break
          
        case 'detail':
          if (!this.formData.detail.trim()) {
            this.errors.detail = '请输入详细地址'
          } else if (this.formData.detail.length < 5) {
            this.errors.detail = '详细地址至少5个字符'
          }
          break
      }
    },
    
    validateForm() {
      this.validateField('name')
      this.validateField('phone')
      this.validateField('detail')
      
      // 验证地区选择
      if (!this.formData.province || !this.formData.city || !this.formData.district) {
        this.errors.region = '请选择所在地区'
      } else if (this.errors.region) {
        // 如果地区已选择，清除错误信息
        this.errors = { ...this.errors }
        delete this.errors.region
      }
      
      return Object.keys(this.errors).length === 0
    },
    
    showRegionPicker() {
      // 由于使用了picker组件，这个方法现在不再需要
      // 点击事件会自动触发picker
      console.log('使用picker组件，无需手动调用')
    },
    
    getCurrentLocation() {
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          // 获取位置成功，可以进行地址解析
        },
        fail: (error) => {
          uni.showToast({
            title: '获取位置失败',
            icon: 'none'
          })
        }
      })
    },
    
    selectFromMap() {
      uni.navigateTo({
        url: '/pages/map/select'
      })
    },
    
    onDefaultChange(e) {
      this.formData.isDefault = e.detail.value
    },
    
    onRegionChange(e) {
      const [province, city, district] = e.detail.value
      this.formData.province = province
      this.formData.city = city
      this.formData.district = district
      
      // 清除地区相关的错误信息
      if (this.errors.region) {
        this.errors = { ...this.errors }
        delete this.errors.region
      }
      
      console.log('选择的地区:', { province, city, district })
    },
    
    async submitForm() {
      if (!this.validateForm()) {
        const firstError = Object.keys(this.errors)[0]
        uni.showToast({
          title: this.errors[firstError],
          icon: 'none'
        })
        return
      }
      
      try {
        uni.showLoading({
          title: this.isEdit ? '保存中...' : '添加中...'
        })
        if(this.addressId){
          this.formData.address_id = this.addressId
        }
        // 模拟API调用
        // await new Promise(resolve => setTimeout(resolve, 1500))
        const res = this.isEdit ? await updateAddress(this.formData) : await addAddress(this.formData)
        uni.hideLoading()
        
        uni.showToast({
          title: this.isEdit ? '修改成功' : '添加成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped>
/* 页面整体样式 */
.address-edit {
  min-height: 100vh;
  background: linear-gradient(180deg, #667eea 0%, #764ba2 100%);
  padding-bottom: 120rpx;
}

/* 页面头部 */
.page-header {
  position: relative;
  height: 200rpx;
  overflow: hidden;
}

.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.header-content {
  position: relative;
  z-index: 2;
  padding: 60rpx 40rpx 40rpx;
  color: #fff;
}

.page-title {
  font-size: 40rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.page-subtitle {
  font-size: 24rpx;
  opacity: 0.8;
}

/* 内容容器 */
.content-container {
  padding: 20rpx;
  margin-top: -40rpx;
  position: relative;
  z-index: 10;
}

/* 表单卡片 */
.form-card {
  background: #fff;
  border-radius: 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.card-header {
  padding: 32rpx;
  border-bottom: 1rpx solid #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-left {
  display: flex;
  align-items: center;
}

.icon-wrapper {
  width: 64rpx;
  height: 64rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;
}

.contact-icon {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
}

.location-icon {
  background: linear-gradient(135deg, #4ecdc4, #44a08d);
}

.setting-icon {
  background: linear-gradient(135deg, #a8edea, #fed6e3);
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #2c3e50;
}

.card-content {
  padding: 32rpx;
}

/* 表单项 */
.form-item {
  margin-bottom: 32rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-row {
  display: flex;
  gap: 24rpx;
}

.form-item.half {
  flex: 1;
}

.item-label {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.label-text {
  font-size: 28rpx;
  color: #2c3e50;
  font-weight: 500;
}

.required {
  color: #e74c3c;
  margin-left: 8rpx;
  font-size: 24rpx;
}

/* 输入框 */
.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.form-input {
  width: 100%;
  height: 88rpx;
  background: #f8f9fa;
  border: 2rpx solid transparent;
  border-radius: 16rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #2c3e50;
  transition: all 0.3s ease;
}

.form-input:focus {
  background: #fff;
  border-color: #667eea;
  box-shadow: 0 0 0 4rpx rgba(102, 126, 234, 0.1);
}

.form-input.error {
  border-color: #e74c3c;
  background: rgba(231, 76, 60, 0.05);
}

.form-input::placeholder {
  color: #bdc3c7;
}

/* 文本域 */
.textarea-wrapper {
  position: relative;
}

.form-textarea {
  width: 100%;
  min-height: 120rpx;
  background: #f8f9fa;
  border: 2rpx solid transparent;
  border-radius: 16rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #2c3e50;
  line-height: 1.6;
  transition: all 0.3s ease;
}

.form-textarea:focus {
  background: #fff;
  border-color: #667eea;
  box-shadow: 0 0 0 4rpx rgba(102, 126, 234, 0.1);
}

.form-textarea.error {
  border-color: #e74c3c;
  background: rgba(231, 76, 60, 0.05);
}

.char-count {
  position: absolute;
  bottom: 16rpx;
  right: 20rpx;
  font-size: 20rpx;
  color: #bdc3c7;
}

/* 选择器 */
.picker-wrapper {
  cursor: pointer;
}

.picker-content {
  height: 88rpx;
  background: #f8f9fa;
  border: 2rpx solid transparent;
  border-radius: 16rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 28rpx;
  color: #2c3e50;
  transition: all 0.3s ease;
}

.picker-content:active {
  background: #fff;
  border-color: #667eea;
}

.picker-content.placeholder {
  color: #bdc3c7;
}

.picker-content.error {
  border-color: #e74c3c;
  background: rgba(231, 76, 60, 0.05);
}

/* 单选组 */
.radio-group {
  display: flex;
  gap: 24rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 12rpx;
  padding: 12rpx 20rpx;
  border-radius: 12rpx;
  background: #f8f9fa;
  transition: all 0.3s ease;
  cursor: pointer;
}

.radio-item.active {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
}

.radio-check {
  width: 32rpx;
  height: 32rpx;
  border: 2rpx solid #dee2e6;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.radio-item.active .radio-check {
  border-color: #667eea;
  background: #667eea;
}

.check-dot {
  width: 12rpx;
  height: 12rpx;
  background: #fff;
  border-radius: 50%;
}

/* 标签组 */
.tag-group {
  display: flex;
  gap: 16rpx;
}

.tag-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 16rpx;
  border-radius: 20rpx;
  background: #f8f9fa;
  color: #7f8c8d;
  font-size: 24rpx;
  transition: all 0.3s ease;
  cursor: pointer;
}

.tag-item.active {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: #fff;
}

/* 开关项 */
.switch-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
}

.switch-info {
  flex: 1;
}

.switch-label {
  font-size: 28rpx;
  color: #2c3e50;
  font-weight: 500;
  display: block;
  margin-bottom: 8rpx;
}

.switch-desc {
  font-size: 24rpx;
  color: #7f8c8d;
  display: block;
}

/* 位置操作 */
.location-actions {
  display: flex;
  gap: 16rpx;
  margin-top: 24rpx;
}

.action-button {
  flex: 1;
  height: 72rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  border-radius: 16rpx;
  font-size: 26rpx;
  transition: all 0.3s ease;
  cursor: pointer;
}

.location-btn {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
}

.location-btn:active {
  background: rgba(102, 126, 234, 0.2);
}

.map-btn {
  background: rgba(39, 174, 96, 0.1);
  color: #27ae60;
}

.map-btn:active {
  background: rgba(39, 174, 96, 0.2);
}

/* 错误提示 */
.error-text {
  font-size: 24rpx;
  color: #e74c3c;
  margin-top: 8rpx;
  display: block;
}

/* 底部提交区 */
.bottom-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 24rpx;
  border-top: 1rpx solid #e9ecef;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
  z-index: 1000;
}

.submit-button {
  height: 88rpx;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.submit-button.disabled {
  background: #bdc3c7;
}

.submit-button:active:not(.disabled) {
  transform: scale(0.98);
}

.submit-text {
  font-size: 32rpx;
  color: #fff;
  font-weight: bold;
}

/* 地区选择器样式 */
.region-picker-component {
  width: 100%;
}
</style>    